import Vue from 'vue';
import Vuex from 'vuex';
import global from './modules/global';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        count: 1,
        num: 5,
        todos: [
            { id: 1, text: '...', done: true },
            { id: 2, text: '...', done: false }
        ],
        obj: {
            id: 1
        }
    },
    mutations: {
        setName (state, payLoad) {
            Vue.set(state.obj, 'name', payLoad);
        },
        increment (state, n = 1) {
            state.count  += n;
        },
        incrementNum (state, n = 1) {
            state.num  += n;
        }
    },
    getters: {
        doneTodos: state => {
            return state.todos.filter(todo => todo.done);
        },
        doneTodosCount: (state, getters) => { // Getter 也可以接受其他 getter 作为第二个参数：
            return getters.doneTodos.length
        },
        getTodoById: (state) => (id) => { // 你也可以通过让 getter 返回一个函数，来实现给 getter 传参。
            return state.todos.find(todo => todo.id === id)
        }
    },
    actions: {
        increment (context, n) { // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
            setTimeout(() => {
                context.commit('increment', n);
            }, 5000);
        },
        async actionsA ({ commit }, n = 0) {
            console.log(n);
            commit('incrementNum', await getData());
        }
        /* ,
        acync actionsAsync ({ dispatch }, n) {
            await dispatch('actionsA');
        } */
    },
    modules: {
        global
    }
});

function getData () {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(120);
        }, 1000);
    })
}